<template>
  <Dialog
    :visible="visible"
    modal
    header="编辑流程定义"
    :style="{ width: '700px' }"
    :closable="true"
    :draggable="false"
    @update:visible="$emit('update:visible', $event)"
    @hide="handleClose"
  >
    <div class="definition-form">
      <form @submit.prevent="handleSubmit">
        <div class="form-row">
          <div class="form-item">
            <label class="form-label required">流程名称</label>
            <InputText
              v-model="formData.name"
              placeholder="请输入流程名称"
              :class="{ 'p-invalid': errors.name }"
            />
            <small v-if="errors.name" class="p-error">{{ errors.name }}</small>
          </div>
          
          <div class="form-item">
            <label class="form-label required">模型标识</label>
            <InputText
              v-model="formData.modelKey"
              placeholder="请输入模型标识(英文)"
              :class="{ 'p-invalid': errors.modelKey }"
            />
            <small v-if="errors.modelKey" class="p-error">{{ errors.modelKey }}</small>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label required">流程分类</label>
            <Dropdown
              v-model="formData.categoryId"
              :options="categoryOptions"
              option-label="label"
              option-value="value"
              placeholder="请选择流程分类"
              size="small"
              :class="{ 'p-invalid': errors.categoryId }"
            />
            <small v-if="errors.categoryId" class="p-error">{{ errors.categoryId }}</small>
          </div>
          
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">版本号</label>
            <InputNumber
              v-model="formData.version"
              placeholder="版本号"
              :min="1"
              disabled
            />
          </div>
          
          <div class="form-item">
            <label class="form-label">删除标志</label>
            <Dropdown
              v-model="formData.delFlag"
              :options="delFlagOptions"
              option-label="label"
              option-value="value"
              placeholder="请选择状态"
              size="small"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item full-width">
            <label class="form-label">流程模型XML</label>
            <Textarea
              v-model="formData.modelXml"
              placeholder="请输入流程模型XML或通过设计器生成"
              :rows="5"
              :auto-resize="true"
            />
          </div>
        </div>
      </form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <Button
          label="取消"
          severity="secondary"
          @click="handleClose"
          :disabled="loading"
        />
        <Button
          label="确定"
          severity="primary"
          @click="handleSubmit"
          :loading="loading"
        />
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import Dialog from 'primevue/dialog'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Dropdown from 'primevue/dropdown'
import Textarea from 'primevue/textarea'

interface DefinitionData {
  id: number
  name: string
  modelKey: string
  categoryId: number
  modelXml: string
  version: number
  delFlag: number
}

interface Props {
  visible: boolean
  definitionData?: DefinitionData | null
  categoryOptions?: any[]
  loading?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: any): void
  (e: 'close'): void
}

const props = withDefaults(defineProps<Props>(), {
  definitionData: null,
  categoryOptions: () => [],
  loading: false
})

const emit = defineEmits<Emits>()

// 表单数据
const formData = reactive({
  id: 0,
  name: '',
  modelKey: '',
  categoryId: null as number | null,
  modelXml: '',
  version: 1,
  delFlag: 0
})

// 表单验证错误
const errors = reactive({
  name: '',
  modelKey: '',
  categoryId: ''
})

// 删除标志选项
const delFlagOptions = [
  { label: '正常', value: 0 },
  { label: '已删除', value: 1 }
]

// 监听visible和definitionData变化
watch([() => props.visible, () => props.definitionData], ([newVisible, newDefinitionData]) => {
  if (newVisible && newDefinitionData) {
    loadDefinitionData(newDefinitionData)
  } else if (newVisible) {
    resetForm()
  }
})

// 加载流程定义数据
const loadDefinitionData = (definitionData: DefinitionData) => {
  Object.assign(formData, {
    id: definitionData.id,
    name: definitionData.name,
    modelKey: definitionData.modelKey,
    categoryId: definitionData.categoryId,
    modelXml: definitionData.modelXml || '',
    version: definitionData.version,
    delFlag: definitionData.delFlag
  })
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    name: '',
    modelKey: '',
    categoryId: null,
    modelXml: '',
    version: 1,
    delFlag: 0
  })
  
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
}

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
  
  // 流程名称验证
  if (!formData.name.trim()) {
    errors.name = '请输入流程名称'
    isValid = false
  } else if (formData.name.length < 2) {
    errors.name = '流程名称至少2个字符'
    isValid = false
  }
  
  // 模型标识验证
  if (!formData.modelKey.trim()) {
    errors.modelKey = '请输入模型标识'
    isValid = false
  } else if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.modelKey)) {
    errors.modelKey = '模型标识只能包含字母、数字和下划线，且必须以字母或下划线开头'
    isValid = false
  }
  
  // 流程分类验证
  if (!formData.categoryId) {
    errors.categoryId = '请选择流程分类'
    isValid = false
  }
  
  return isValid
}

// 处理提交
const handleSubmit = () => {
  if (!validateForm()) {
    return
  }
  
  emit('submit', { ...formData })
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}
</script>

<style scoped>
.definition-form {
  padding: 20px 0;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-item.full-width {
  flex: 1 1 100%;
}

.form-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-label.required::after {
  content: ' *';
  color: #ff4d4f;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单组件样式覆盖 */
:deep(.p-inputtext),
:deep(.p-inputnumber),
:deep(.p-dropdown),
:deep(.p-inputtextarea) {
  height: 40px;
  font-size: 14px;
}

:deep(.p-inputtextarea) {
  height: auto;
  min-height: 120px;
}

:deep(.p-inputnumber .p-inputtext) {
  height: 40px;
}

:deep(.p-error) {
  font-size: 12px;
  margin-top: 4px;
}

/* 下拉框选项字体样式 */
:deep(.p-dropdown-panel .p-dropdown-items .p-dropdown-item) {
  font-size: 14px !important;
  line-height: 20px !important;
  padding: 8px 12px !important;
}

/* 下拉框placeholder样式 */
:deep(.p-dropdown .p-dropdown-label.p-placeholder) {
  font-size: 14px !important;
  line-height: 20px !important;
  color: #6c757d !important;
}
</style>
